import request from "@/utils/request";
import bus from "@/components/common/bus"

let socket = undefined;
let url = "ws:"+request.projecturl+"/socket/";
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = () => {
    socket && socket.close();
    if (typeof (WebSocket) === "undefined") {
        console.log("您的浏览器不支持websocket")
        return
    }
    let token = localStorage.getItem('userNike')
    // if (!token) {
    //     console.log("未登录")
    //     return;
    // }
    socket = new WebSocket(url + token)
    socket.onopen = onopenWS
    socket.onmessage = onmessageWS
    socket.onerror = onerrorWS
    socket.onclose = oncloseWS
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
    console.log("socket连接成功")
}

/**连接失败重连 */
const onerrorWS = () => {
    socket && socket.close();
    console.log('连接失败重连中')
    if (socket.readyState !== 3) {
        socket = null
        createSocket()
    }
}

/**WS数据接收统一处理 */
const onmessageWS = e => {
    let msg = JSON.parse(e.data);
    if (msg.code === '0') {
        bus.$emit('onwsmessage', msg);
    } else {
        console.log('ws 初始化连接成功：' + msg.msg);
    }
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
    setTimeout(() => {
        if (socket.readyState === 0) {
            connecting(message)
        } else {
            socket.send(JSON.stringify(message))
        }
    }, 1000)
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
    if (socket !== null && socket.readyState === 3) {
        socket.close()
        createSocket()
    } else if (socket.readyState === 1) {
        socket.send(JSON.stringify(message))
    } else if (socket.readyState === 0) {
        connecting(message)
    }
}

/**断开重连 */
const oncloseWS = () => {
    console.log('websocket已断开')
}
